<template>
  <div class="message-edit" @click.stop="">
    <AtWho
      :maxlength="maxLength"
      v-model="commentText"
      :noRichText="true"
      :placeholder="placeholder"
      :pushPeopleList="pushPeopleList"
      ref="atWhoRef"
      :fixRows="true"
      :rows="rows" />
    <CommentSelectPeople
      v-if="isShowSelectPeople"
      type="@"
      @close="isShowSelectPeople = false"
      :dataList="pushPeopleList.slice(1)"
      @selected="
        (selectedList) => {
          commentText += getPeopleListContent(selectedList.map((d) => `@${d} `).join(''));
          isShowSelectPeople = false;
        }
      " />
    <div class="attitude-content-handle">
      <a-dropdown
        placement="topLeft"
        v-if="isShowUploadAttachment || isShowRelAttachment || isShowRelDoc">
        <a-menu slot="overlay">
          <a-menu-item v-if="isShowUploadAttachment">
            <!-- TODO:附件 -->
            <UploadAtt
              placement="topLeft"
              :fileList="attachments"
              :isSetSecretLevel="!baseInfo.secretLevel.hidden"
              :request="{
                upload: api.uploadFileUpload,
                getState: api.uploadGetFileState
              }"
              :maxSize="baseInfo.businessData.other.fileUploadMaxSize"
              style="height: 21px"
            />
          </a-menu-item>
          <a-menu-item v-if="isShowRelAttachment">
            <RelationAttachment :fileList="attachments" @selected="handleSelectAttachment" />
          </a-menu-item>
          <a-menu-item v-if="isShowRelDoc">
            <RelationDoc @selected="(dataList) => (relationDocs = dataList)" :area="docArea"
          /></a-menu-item>
        </a-menu>
        <i class="syIcon sy-attachment"></i>
      </a-dropdown>
      <i @click="isShowSelectPeople = true" class="syIcon sy-at"></i>
      <!-- 意见隐藏 -->
      <div>
        <HideOpinion
          :isHideOpinion.sync="isHideOpinion"
          :hideOpinionObject.sync="hideOpinionObject"
          :isSiderHideOption="isSiderHideOption" />
      </div>
    </div>
    <!-- 附件列表 -->
    <FileList
      :isDisplayAllDownload="false"
      :isInlineLayout="false"
      :attachments="attachments"
      :relationDocs="relationDocs"
      :areaName="getDocArea(item)"
      :listStyle="{ maxHeight: '238px', overflowY: 'auto' }"
    />
    <div class="message-edit-btns">
      <a-button class="setting-button" @click="submit" :loading="loading">
        {{ this.$i18n('common.button.reply.label') }}
      </a-button>
      <a-button @click="cancel"> {{ this.$i18n('common.toolbar.cancelmt.label') }}</a-button>
    </div>
  </div>
</template>
<script>
  // 引入@人组件
  import AtWho from '@/components/atom/at-who';
  // 引入基础数据
  import { useBaseInfoStore } from '@/store/modules/base-info.js';
  // 引入相关数据
  import { useSummaryCommentStore } from '@/store/modules/summary/comment.js';
  import { mapActions, mapState, mapWritableState } from 'pinia';
  import api from '@/api';
  // 意见隐藏
  import HideOpinion from '@/components/atom/hide-opinion';
  // 上传附件
  import UploadAtt from '@/components/upload-att';
  // 关联附件
  import RelationAttachment from '@/components/relation-attachment';
  // 关联文档
  import RelationDoc from '@/components/relation-doc';
  //引入关联文档对象操作
  import { clearArea } from '@/helper/relation-doc';
  //引入附件、关联列表集合
  import FileList from '@/components/classic-layout/summary/file-new';
  import globalData from '@/plugins/data';
  //引入常用语弹出内容组件
  // import CommonPhrases from '@/components/classic-layout/summary/handle-right-new/components/textarea/components/common-phrases';
  //引入富文本相关操作
  import { transformHTML } from '@/components/classic-layout/summary/handle-right-new/components/textarea/components/rich-text/helper';
  //引入选人弹窗
  import CommentSelectPeople from '@/components/dialog/select-people';

  export default {
    name: 'MessageEdit',
    components: {
      AtWho,
      HideOpinion,
      UploadAtt,
      RelationAttachment,
      RelationDoc,
      FileList,
      // CommonPhrases,
      CommentSelectPeople
    },
    props: {
      activeKey: {
        type: Number,
        default: 1
      },
      //评论回复对象
      item: {
        type: Object
      },
      rootId: {
        type: Number
      },
      // placeholder: {
      //   type: String
      // },
      // maxLength: {
      //   type: Number
      // },
      //可选取推送人员列表
      pushPeopleList: {
        type: Array
      },
      isSetSecretLevel: {
        type: Boolean
      }
    },
    computed: {
      ...mapState(useBaseInfoStore, ['pushPeopleList', 'baseInfo']),
      ...mapWritableState(useSummaryCommentStore, ['isPigeonhole', 'dealDepartmentIndex']),
      isPostscript() {
        return false;
      },
      docArea() {
        if (this.isPostscript) {
          return 'addPostscript';
        }
        //输入框存在地情况下，又点了回复其他人，再获取焦点
        this.$refs.atWhoRef?.focus();
        return this.item ? `reply-${this.item.id}-create` : '';
      },
      isShowUploadAttachment() {
        return this.baseInfo.businessData.nodePolicy.canUploadAttachment;
      },
      isShowRelAttachment() {
        return this.baseInfo.businessData.nodePolicy.canUploadRelAttachment;
      },
      isShowRelDoc() {
        return this.baseInfo.businessData.nodePolicy.canUploadRelDoc;
      }
    },
    data() {
      return {
        // 输入框相关属性
        maxLength: 2000,
        placeholder: this.$i18n(
          'collaboration.opinion.reply.to',
          this.item.commentSubmitParams.createName
        ),
        //对那些人隐藏意见
        hideOpinionObject: {
          //0.1绝密、0.2绝密、0.3绝密、1.1秘密、0.4
          text: '',
          //Member|-8067040239322578063,Member|-7716299150402043535
          value: ''
        },
        isHideOpinion: false,
        isShowSelectPeople: false,
        isRichText: false,
        //关联文档列表
        relationDocs: [],
        //上传附件列表
        attachments: [],
        //文本框的值
        commentText: '',
        //消息推送
        isPushMessage: true,
        rows: 3,
        loading: false,
        isSiderHideOption: true
      };
    },
    created() {
      // 初始化数据
      this.initData();
      //意见隐藏不包含发起者自己
      this.api = api;
    },
    mounted() {
      // 获取焦点
      // this.$refs.atWhoRef
      setTimeout(() => {
        this.$refs.atWhoRef?.focus();
      }, 0);
    },
    methods: {
      ...mapActions(useBaseInfoStore, ['validateAttachmentUploading']),
      getDocArea(item) {
        return `reply-${item.id}-create`;
      },
      /**
       * @description: 将传入推送人员列表按照富文本或者普通文本进行返回
       * @param {Array} list 传入人员列表
       * @return {String}返回字符串
       */
      getPeopleListContent(text) {
        console.log(text);

        if (this.isRichText) {
          return transformHTML(text);
        }
        return text;
      },
      richTextSwitch() {
        //如果是富文本切换成普通文案
        if (this.isRichText) {
          //转成纯文本
          this.commentText = this.$refs.atWhoRef.$refs.richText.getText();
        }
        // 富文本改成在组件里面自己转
        // else {
        //     //普通文案切换成富文本
        //     this.commentText = transformHTML(this.commentText);
        // }
        this.isRichText = !this.isRichText;
      },
      initData() {
        if (this.item) {
          const senderUser = this.baseInfo.businessData.senderUser;
          // console.log('senderUser ', senderUser);
          console.log('item ', this.item);
          // this.item.hidden !== null && (this.isHideOpinion = this.item.hidden);
          if (this.item.createId !== senderUser.id) {
            this.hideOpinionObject = {
              value: this.item.createId + ',' + senderUser.id,
              text: this.item.createName + ',' + senderUser.name
            };
          } else {
            this.hideOpinionObject = {
              value: this.item.createId,
              text: this.item.createName
            };
          }

          this.placeholder = `${this.$i18n('common.button.reply.label')} ${this.item.createName}`;
        }
        // 清除临时关联文档的存储
        clearArea(this.docArea);
      },
      submit() {
        if (this.isPostscript) {
          this.submitPostscript();
        } else {
          this.submitComment();
        }
      },
      cancel() {
        this.$emit('cancel');
      },
      // 更新关联附件
      handleSelectAttachment(attachmentList) {
        this.attachments.push(...attachmentList);
      },
      /**
       * @description: 提交评论
       * @param {*}
       * @return {*}
       */
      async submitComment() {
        //意见不能为空
        if (!this.commentText) {
          this.$message.error(this.$i18n('collaboration.common.deafult.commonNotNull'));
          return;
        }
        if (!this.validateAttachmentUploading()) {
          return;
        }
        this.loading = true;
        // 过滤pushMessageUserIds数据
        const pushMessageUserIds = this.$refs.atWhoRef.getMentionList().map((d) => d.memberId);
        // 意见隐藏：人员信息
        const showToId = this.hideOpinionObject.value;
        const submitObj = {
          replyToId: this.item.createId, // 创建评论人的id
          moduleId: this.item.moduleId, // 模块id
          pid: this.rootId, // 上级评论意见id
          content: this.commentText, // 评论的内容
          affairId: globalData.affairId, // 事项id
          // pushMessage: pushMessageUserIds.length !== 0, // 是否推送消息
          pushMessageUserIds, // at通知的用户id列表
          assDocDomain: this.relationDocs, //关联文档列表
          attFileDomain: this.attachments, // 附件列表
          pushMessage: true,
          showToId, // 允许让谁看见此消息
          subType: '0', // 0：人员节点处理的意见; 1: 超级节点自动生产的意见
          ctype: '1', // 意见类型: 回复
          hidden: this.isHideOpinion // 是否隐藏意见
        };
        //评论成功，直接把数据加进去
        let submitComment = await api.commentCommitComment(submitObj);
        //清空页面数据
        this.commentText='';
        this.relationDocs=[];
        this.attachments=[];
        this.isHideOpinion=false;
        this.$emit('addReply', submitComment);
        this.loading = false;
      }
    }
  };
</script>
<style lang="scss">
  .message-edit {
    .ant-mentions {
      border-top: 1px solid #e9ebee;
      border-right: 1px solid #e9ebee;
      border-left: 1px solid #e9ebee;
      border-bottom: 0;
      box-shadow: none !important;
    }
  }
</style>
<style scoped lang="scss">
  .message-edit {
    width: 100%;
    background: #f1f4f7;
    padding: 12px 16px 0;

    > .attitude-content-handle {
      padding: 2px;
      overflow: hidden;
      color: $c9;
      background-color: #fff;
      border: $border;
      border-top: 0;

      > i.sy-attachment {
        float: left;
        padding: 8px 10px;
        cursor: pointer;
      }

      > i.sy-at {
        float: left;
        padding: 8px 16px 8px 6px;
        cursor: pointer;
      }

      > .sy-editor {
        float: right;
        border-radius: 4px;
      }

      > .common-phrases-btn {
        color: $primary-color;
      }
    }
    .message-edit-btns {
      padding: 12px 0;
      text-align: right;
      .setting-button {
        margin-right: 10px;
        border: 1px solid #1890ff;
        color: #1890ff;
        border: 1px solid var(--theme-brand6, #1890ff);
        color: var(--theme-brand6, #1890ff);
      }
      .setting-button:hover {
        border: 1px solid #40a9ff;
        color: #40a9ff;
        border: 1px solid var(--theme-brand6, #40a9ff);
        color: var(--theme-brand6, #40a9ff);
      }
    }
  }
</style>
